package com.itic.mall.mobile.users.address;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.users.address.persistence.model.Usersaddress;
import com.itic.mall.system.users.address.persistence.model.UsersaddressExample;
import com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria;
import com.itic.mall.system.users.address.service.UsersaddressService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;

/**
 * 用户地址信息管理接口
 * @author Administrator
 * @time 2017-12-5
 */

@Controller
@RequestMapping(value="/mobile/users/address")
public class UsersaddressInterface extends BaseMobileInterface{
	
    private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "updateTime", "orgCode","userId","reorder","createTime" };

	@Autowired 
	private UsersaddressService usersaddressService;
	/**
	 * 新增用户地址信息
	 * @param userid
	 * @param userNickname
	 * @param city
	 * @param street
	 * @param detail
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/add")
    @ResponseBody
	public Map<String, Object> add(HttpServletRequest request, HttpServletResponse response, String token, String appId,
			String receiverName, String city, String detail, String receiverPhone, String isdefault) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = FAIL;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);				
				if (null != usersMall) {
					String userId = usersMall.getId();
					Usersaddress usersaddress = new Usersaddress();
					if (StringHelper.isNotBlank(receiverName) && StringHelper.isNotBlank(city)
							&& StringHelper.isNotBlank(detail) && StringHelper.isNotBlank(receiverPhone)) {
						usersaddress.setUserId(usersMall.getId());
						usersaddress.setUserNickName(usersMall.getUserNickName());
						usersaddress.setReceiverName(receiverName);
						usersaddress.setCity(city);
						usersaddress.setDetail(detail);
						usersaddress.setReceiverPhone(receiverPhone);
						usersaddress.setIsDefaultAddress(isdefault);
						// 如果默认地址属性为真，则先把其他地址置为非默认地址
						if (StringHelper.isNotBlank(isdefault) && "1".equals(isdefault)) {
							UsersaddressExample example = new UsersaddressExample();
							Criteria criteria = example.createCriteria();
							criteria.andIsEffectiveEqualTo(DBConst.TRUE);
							criteria.andUserIdEqualTo(userId);
							List<Usersaddress> list = usersaddressService.list(example);
							if (list.size() > 0) {
								for (Usersaddress useraddr : list) {
									if (useraddr.getIsDefaultAddress().equals(DBConst.TRUE)) {
										useraddr.setIsDefaultAddress(DBConst.FALSE);
										result = usersaddressService.edit(useraddr);
									}
								}
							}
						}else{
							UsersaddressExample example = new UsersaddressExample();
							Criteria criteria = example.createCriteria();
							criteria.andIsEffectiveEqualTo(DBConst.TRUE);
							criteria.andUserIdEqualTo(userId);
							List<Usersaddress> list = usersaddressService.list(example);
							if (list.isEmpty()) {
								usersaddress.setIsDefaultAddress(DBConst.TRUE);
							}
						}
						result = usersaddressService.add(usersaddress);
						if (result.equals(SUCCESS)) {
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}

					}
				} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}

		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersaddressInterface", "add", e.toString(), "新建收货地址", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 用户地址编辑
	 * @param userid
	 * @param userNickname
	 * @param city
	 * @param street
	 * @param detail
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/edit")
    @ResponseBody
	public Map<String, Object> edit(HttpServletRequest request, HttpServletResponse response, String token,
			String appId, String receiverName, String city, String addrId, String detail, String receiverPhone,
			String isdefault) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = FAIL;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(addrId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userId = usersMall.getId();
					UsersaddressExample example = new UsersaddressExample();
					Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andUserIdEqualTo(userId);
					criteria.andIdEqualTo(addrId);
					List<Usersaddress> list = usersaddressService.list(example);
					if (list.size() > 0) {
						Usersaddress usersaddress = list.get(0);
						if (StringHelper.isNotBlank(receiverName)) {
							usersaddress.setReceiverName(receiverName);
						}
						if (StringHelper.isNotBlank(receiverPhone)) {
							usersaddress.setReceiverPhone(receiverPhone);
						}
						if (StringHelper.isNotBlank(city)) {
							usersaddress.setCity(city);
						}
						if (StringHelper.isNotBlank(detail)) {
							usersaddress.setDetail(detail);
						}
						result = usersaddressService.edit(usersaddress);
						if (StringHelper.isNotBlank(isdefault)) {
							if("1".equals(isdefault))
								result = setdefaultAddrByAddrId(request, response, userId, addrId);
							if("0".equals(isdefault)){
								UsersaddressExample userExample = new UsersaddressExample();
								Criteria userCriteria = example.createCriteria();
								userCriteria.andIsEffectiveEqualTo(DBConst.TRUE);
								userCriteria.andUserIdEqualTo(userId);
								userCriteria.andIdNotEqualTo(addrId);
								List<Usersaddress> addressList = usersaddressService.list(userExample);
								if(addressList.isEmpty())
									result = setdefaultAddrByAddrId(request, response, userId, addrId);
								else{
									Usersaddress address = addressList.get(0);
									address.setIsDefaultAddress(DBConst.TRUE);
									this.usersaddressService.edit(address);
								}
									
							}	
						}
						if (result.equals(SUCCESS)) {
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}
					} else {
						errorCode = RECEIVER_ERROR_CODE;
						errorMsg = RECEIVER_ERROR_MSG;
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsersaddressInterface", "edit", e.toString(),"用户地址编辑",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	/**
	 * 用户地址删除
	 * @param userid
	 * @param userNickname
	 * @param city
	 * @param street
	 * @param detail
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/del")
    @ResponseBody
	public Map<String,Object> delete(HttpServletRequest request,HttpServletResponse response,String addrId){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	   		Usersaddress usersaddress = new Usersaddress();
	   		usersaddress.setId(addrId);
	   		String result = usersaddressService.delete(usersaddress);
	   		if(result.equals(SUCCESS)){
	   			errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsersaddressInterface", "del", e.toString(),"用户地址删除",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	/**
	 * 用户收货地址列表
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/addrlist")
    @ResponseBody
	public Map<String,Object> addrlist(HttpServletRequest request,HttpServletResponse response,String token,String appId){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
   			UsersMall usersMall = getUsersByTokenAndAppId(token,appId);
			if (usersMall != null) {
				String userId = usersMall.getId();
				UsersaddressExample example = new UsersaddressExample();
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andUserIdEqualTo(userId);
				List<Usersaddress> list = usersaddressService.list(example);
				resultMap.put(DATA, ValueHelper.tranList2MapList(list, ignoreProperties));
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
			} else {
				errorCode = LOGIN_ERROR_CODE;
   				errorMsg = LOGIN_ERROR_MSG;
   			}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UsersaddressInterface", "addrlist", e.toString(),"收货地址列表",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
	    isCrrossDomain(response);
	    return resultMap;
	}
	
	public String setdefaultAddrByAddrId(HttpServletRequest request, HttpServletResponse response,String userId, String addrId) {
		String result = FAIL;
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
		try {
			UsersaddressExample example = new UsersaddressExample();
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andUserIdEqualTo(userId);
			List<Usersaddress> list = usersaddressService.list(example);
			if (list.size() > 0) {
				for (Usersaddress useraddr : list) {
					if (useraddr.getId().equals(addrId)) {
						useraddr.setIsDefaultAddress(DBConst.TRUE);
					} else {
						useraddr.setIsDefaultAddress(DBConst.FALSE);
					}
					result = usersaddressService.edit(useraddr);
					if (SUCCESS.equals(result)) {
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					} else {
						break;
					}
				}
			} else {
				errorCode = USERS_ADDRESS_ERROR_CODE;
				errorMsg = USERS_ADDRESS_ERROR_MSG;
			}

		} catch (Exception e) {
			logException(errorCode, errorMsg, e.toString(), "设置默认地址", e);
		}
		return result;
		}
	/**
	 * 设置默认地址
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/addDefaultAddr")
	@ResponseBody
	public Map<String, Object> addDefaultAddr(HttpServletRequest request, HttpServletResponse response,String token,String appId, String addrId) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = FAIL;
		try {
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(addrId)){
	   			UsersMall usersMall = getUsersByTokenAndAppId(token,appId);
	   			if(usersMall != null){
	   				String userId = usersMall.getId();
	   				result = setdefaultAddrByAddrId(request,response,userId,addrId);
					if(SUCCESS.equals(result)){
						errorCode = SUCCESS_ERROR_CODE;
	   			       	errorMsg = SUCCESS_ERROR_MSG;
					}
	   			}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
			
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersaddressInterface", "addDefaultAddr", e.toString(), "设置默认地址", e);
		}
		resultMap.put(CODE,errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	    }
}
